package andreafrancia.util;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;

/**
 *
 * @author Andrea
 */
public class ToStringHelper {

    public static String toString(Object o) {
        StringBuilder sb = new StringBuilder();
        sb.append(o.getClass().getSimpleName());
        sb.append('[');

        BeanInfo info;
        try {
            info = Introspector.getBeanInfo(o.getClass(), Object.class);
            for (int i = 0; i < info.getPropertyDescriptors().length; i++) {
                PropertyDescriptor pd = info.getPropertyDescriptors()[i];
                if (pd.getReadMethod() != null) {
                    sb.append(pd.getName());
                    sb.append(":");
                    try {
                        sb.append(pd.getReadMethod().invoke(o));
                    } catch (IllegalAccessException ex) {
                        sb.append(ex.getClass().getSimpleName());
                    } catch (IllegalArgumentException ex) {
                        sb.append(ex.getClass().getSimpleName());
                    } catch (InvocationTargetException ex) {
                        sb.append(ex.getClass().getSimpleName());
                    }
                    if (i < info.getPropertyDescriptors().length - 1) {
                        sb.append(", ");
                    }
                }
            }
        } catch (IntrospectionException ex) {
            sb.append("problems");
        }
        sb.append(']');
        return sb.toString();
    }
}
